<?php

date_default_timezone_set('UTC');

require_once("../data/conf/config.php");

function __autoload($class_name) {
    $file = sprintf( "%s/lib/%s.class.php", YOULOC_DATA, $class_name );
    if( file_exists( $file ) && is_readable( $file ) ) {
        require_once YOULOC_DATA.'/lib/'.$class_name . '.class.php';
    }
}


ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . YOULOC_DATA."/external/");


$dsn = sprintf('mysql:host=%s;dbname=%s',$mysql_host, $mysql_db);
$dbh = new PDO($dsn,$mysql_user,$mysql_pass);


$user = new user();


function distance($lat1, $lon1, $lat2, $lon2) {
        return (6367*pi()*sqrt(($lat2-$lat1)*($lat2-$lat1)+cos($lat2/(180/pi()))*cos($lat1/(180/pi()))*($lon2-$lon1)*($lon2-$lon1))/180);
}

function sanitize($string) {
	$string = trim($string);
	$string = htmlentities($string);
	return $string;
}


function reverseGeocode($lat,$lon) {
        $dom = new domDocument;
        $url = sprintf("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=%s&max=1&any=1", urlencode(sprintf("suburb near %f, %f", $lat, $lon)));

        $dom->loadXML(file_get_contents($url));

        if (!$dom) {
                return null;
        }

        $s = simplexml_import_dom($dom);
        $name = trim(eregi_replace("\[.+\]","", $s->named[0]["name"]));
        $distance = (float)$s->named[0]->place[0]->named[0]["distance"];
        $city = trim(eregi_replace("\[.+\]","",$s->named[0]->nearestplaces[0]->named[0]->nearestplaces[0]->named[0]["name"]));
        $country = trim(eregi_replace("\[.+\]|\ in\ ","",$s->named[0]->nearestplaces[0]->named[0]->nearestplaces[0]->named[0]["is_in"]));
        if ( !empty($name) && $distance < 5 ) {
		if ($distance > 1) $name = "In";
                return sprintf("%s%s%s", $name, $city ? " $city" : "" , $country ? " $country" : "" );
	} else {
                return "unknown";
	}
}


function updateLocation($place, $track_id, $location_id) {
	global $dbh;
	$sql = "SELECT lat, lon FROM gps_data WHERE id = ? LIMIT 1;";
	$stmt = $dbh->prepare($sql);
	$stmt->execute(array($location_id));
	$row = $stmt->fetch();

	$location = "";
	if ($location = reverseGeocode($row["lat"], $row["lon"])) {
		$stmt = null;
		$sql = "";
		if ($place == "start_place") $sql = "UPDATE tracks SET start_place = ? WHERE track_id = ? LIMIT 1;";
		if ($place == "end_place") $sql = "UPDATE tracks SET end_place = ? WHERE track_id = ? LIMIT 1;";
		$stmt = $dbh->prepare($sql);
		$stmt->execute(array($location, $track_id));
		return $location;	
	} else {
		return "unknown";
	}
}

class BaseIntEncoder {
	//This implementation is from Travell Perkins, http://travellperkins.com/
	//Use this to code id's to "unguessable" short strings.
	/* Example:
	BaseIntEncoder::encode('1122344523');//result:3IcjVE
	BaseIntEncoder::decode('3IcjVE');//result:1122344523
	*/

	//const codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	//readable character set excluded (0,O,1,l)
	//const codeset = "23456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";
	const codeset = "iVp2TnqXAxMEgudCNJFDWvKoZwQfL9c5HYtbeUI4SRjymP86hsz7akB3rG"; //Randomized codeset to make quessing more difficult


	static private function check_bcmath() {
		if (!function_exists("bcmod")) {
			return FALSE;
			trigger_error("BCmath functions missing.", E_USER_NOTICE);
		} else {
			return TRUE;
		}
	}

	static function encode($n) {
		if (!self::check_bcmath()) {
			return FALSE;
		}
		$base = strlen(self::codeset);
		$converted = '';
		while ($n > 0) {
			$converted = substr(self::codeset, bcmod($n,$base), 1) . $converted;
			$n = self::bcFloor(bcdiv($n, $base));
		}
		return $converted;
	}

	static function decode($code) {
		if (!self::check_bcmath()) {
			return FALSE;
		}
		$base = strlen(self::codeset);
		$c = '0';
		for ($i = strlen($code); $i; $i--) {
        	    $c = bcadd($c,bcmul(strpos(self::codeset, substr($code, (-1 * ( $i - strlen($code) )),1)),bcpow($base,$i-1)));
		}
		return bcmul($c, 1, 0);
	}

	static private function bcFloor($x) {
		return bcmul($x, '1', 0);
	}

	static private function bcCeil($x) {
		$floor = bcFloor($x);
		return bcadd($floor, ceil(bcsub($x, $floor)));
	}

	static private function bcRound($x) {
	$floor = bcFloor($x);
	return bcadd($floor, round(bcsub($x, $floor)));
	}
}

	function fix_time($string) {
		if (preg_match('/^([\\d]{2})([\\d]{2})([\\d]{2})/', $string, $regs)) {
			return $regs[1].":".$regs[2].":".$regs[3];
		} else {
			return "";
		}
	}

   
function fix_date($string) {
	if (preg_match('/^([\\d]{2})([\\d]{2})([\\d]{2,4})$/', $string, $regs)) {
		$date = "";
		if (strlen($regs[3]) == 2) {
			$date .= "20".$regs[3];
		} else {
			$date .= $regs[3];
		}
		return $date."-".$regs[2]."-".$regs[1];
;
	} else {
		return "";
	}
}


// common variables for templates
$variables['SITE_URL'] = $site_url;
$variables['API_URL'] = $api_url;
$variables['GOOGLE_ANALYTICS'] = $google_analytics_key;
$variables["RAND"] = rand(); // Force reaload of stylesheets and javascript every time..

?>
